package com.paic.custserv.web.controller.executive;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.aspectj.util.LangUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSONObject;
import com.paic.custserv.common.Constant;
import com.paic.custserv.common.Constant.RoleEnum;
import com.paic.custserv.common.ResultMap;
import com.paic.custserv.common.enums.StatusEnum;
import com.paic.custserv.common.enums.WorkOrderStatus;
import com.paic.custserv.domain.AppUser;
import com.paic.custserv.domain.CussWorkOrder;
import com.paic.custserv.domain.CussWorkOrderDealflow;
import com.paic.custserv.domain.Page;
import com.paic.custserv.domain.UserVO;
import com.paic.custserv.service.ICussWorkOrderService;
import com.paic.custserv.utils.AuthenticationUtils;
import com.paic.custserv.utils.CommonUtil;
import com.paic.custserv.utils.redis.RedisCacheService;
import com.paic.custserv.web.controller.vo.CussWorkOrderQueryVO;

/**
 * 工单生成及查询
 * @author ZOUHUIQUN470
 *
 */
@RequestMapping("executive/workorder")
@Controller
public class CussWorkOrderController {
	private static final Logger logger = LoggerFactory.getLogger(CussWorkOrderController.class);
	
	@Autowired
	private ICussWorkOrderService cussWorkOrderService;	
	
	@Autowired
	private RedisCacheService redisCacheService;
	
     /**
      * 待处理工单
      * @author 胡启萌
      * @date 2015年9月15日
      */
     @RequestMapping("pending.do")
	 public String pendingWorkOrder(Model model) {
		 model.addAttribute("optype", "pending");
		 return "executive/pending";
	 }
          
     /**
      * 分页查询待处理工单
      * @author 胡启萌
      * @date 2015年9月17日
      */
     @RequestMapping("pending/query.do")
 	 public @ResponseBody ResultMap pendingQuery(CussWorkOrderQueryVO vo) {
    	 try{
    		vo.setMuchWorkOrderStatus(Constant.MUCH_PENDING_WORK_ORDER_STATUS);
  			return new ResultMap(StatusEnum.success, 
  					queryWorkOrderByType(vo, WorkOrderStatus.Pending));
  		}catch(Exception e) {
  			logger.error("客户专员分页查询待处理工单出错:{}", e);
  		}
 		return new ResultMap(StatusEnum.fail);
 	 }
	 
	 /**
	  * 已关闭工单
	  * @author 胡启萌
	  * @date 2015年9月15日
	  */
	 @RequestMapping("closed.do")
	 public String closedWorkOrder(Model model) {
		 model.addAttribute("optype", "closed");
		 return "executive/closed";
	 }
	 
	 /**
	  * 分页查询已关闭工单
	  * @author 胡启萌
	  * @date 2015年9月17日
	  */
	 @RequestMapping("closed/query.do")
 	 public @ResponseBody ResultMap closedQuery(CussWorkOrderQueryVO vo) {
		try{
			return new ResultMap(StatusEnum.success, 
  					queryWorkOrderByType(vo, WorkOrderStatus.Closed));
 		}catch(Exception e) {
 			logger.error("客户专员分页查询已关闭工单出错:{}", e);
 		}
 		return new ResultMap(StatusEnum.fail);
 	 }
	 
	 /**
	  * 审核中工单
	  * @author 胡启萌
	  * @date 2015年9月15日
	  */
	 @RequestMapping("audit.do")
	 public String auditWorkOrder(Model model) {
		 model.addAttribute("optype", "audit");
		 return "executive/audit";
	 }
	 
	 /**
	  * 分页查询审核中工单
	  * @author 胡启萌
	  * @date 2015年9月17日
	  */
	 @RequestMapping("audit/query.do")
 	 public @ResponseBody ResultMap auditQuery(CussWorkOrderQueryVO vo) {
		try{
			return new ResultMap(StatusEnum.success, 
  					queryWorkOrderByType(vo, WorkOrderStatus.Audit));
 		}catch(Exception e) {
 			logger.error("客户专员分页查询审核中工单出错:{}", e);
 		}
 		return new ResultMap(StatusEnum.fail);
 	 }
	 
	 /**
	  * 全部工单
	  * @author 胡启萌
	  * @date 2015年9月15日
	  */
	 @RequestMapping("whole.do")
	 public String wholeWorkOrder(Model model) {
		 model.addAttribute("optype", "whole");
		 return "executive/whole";
	 }
	 
	 /**
	  * 分页查询全部工单
	  * @author 胡启萌
	  * @date 2015年9月17日
	  */
	 @RequestMapping("whole/query.do")
 	 public @ResponseBody ResultMap wholeQuery(CussWorkOrderQueryVO vo) {
 		try{
 			return new ResultMap(StatusEnum.success, 
  					queryWorkOrder(vo));
 		}catch(Exception e) {
 			logger.error("客户专员查询全部工单出错:{}", e);
 		}
 		return new ResultMap(StatusEnum.fail);
 	 }			
	
	/**
	 * 查询工单
	 */	
	@RequestMapping(value = "/queryCussWorkOrder", method = {RequestMethod.GET,RequestMethod.POST})
	public @ResponseBody Page queryCussWorkOrder(HttpServletRequest request,HttpServletResponse response){				
		String temppage=request.getParameter("currentPage");
		Integer pageSize=1;  
		Page page = Page.initPage(temppage,pageSize);
	
		String userRole=AuthenticationUtils.getCurrentUser().getUserRole();
		String userAccount=AuthenticationUtils.getCurrentUser().getUserUMID();
		
		String opType=request.getParameter("opType");
		String workOrderCode=request.getParameter("workOrderCode");
		String workOrderTypeId=request.getParameter("workOrderTypeId");
		String workOrderIssuDesc=request.getParameter("workOrderIssuDesc");
		
		//根据工单类型，找所有的工单子类型
		List<Integer> typelistList=null;		
		if(!CommonUtil.isBlank(workOrderTypeId)){
			typelistList=new ArrayList<Integer>();
			typelistList.add(Integer.valueOf(workOrderTypeId));
			List<Map<String,Object>> cussWorkOrderTypeList=cussWorkOrderService.selectByParentType(Integer.valueOf(workOrderTypeId));
			if(cussWorkOrderTypeList !=null &&cussWorkOrderTypeList.size()>0)
			for(Map<String,Object> temp:cussWorkOrderTypeList){
				typelistList.add(Integer.valueOf(temp.get("typeId").toString()));
			}
		};
		
		List<CussWorkOrder> cussWorkOrderList =null;
		//设置参数
		Map<String,Object> paramMap=new HashMap<String,Object>();
		paramMap.put("serialNumber", workOrderCode);
		paramMap.put("typeId", typelistList);
		paramMap.put("issuDesc", workOrderIssuDesc);
		
		//客服专员，查看自己所要处理的工单
		if(RoleEnum.ORDER_EXECUTOR.getCode().equals(userRole))
			paramMap.put("currOperatorUm", userAccount);
		else paramMap.put("currOperatorUm", null);
			
		try{	
			if("whole".equals(opType)){//查询所有工单
				String isEvaluate=request.getParameter("isEvaluate");
				String customerEvaluate=request.getParameter("customerEvaluate");
				String approveStatus=request.getParameter("approveStatus");
				paramMap.put("isEvaluate", isEvaluate);
				paramMap.put("customerEvaluate", customerEvaluate);
				paramMap.put("approveStatus", approveStatus);
				cussWorkOrderList =cussWorkOrderService.selectByParam(page,paramMap);								
			}
			if("pending".equals(opType)){//待处理工单
				paramMap.put("workOrderStatus", WorkOrderStatus.Pending.getValue());
				cussWorkOrderList =cussWorkOrderService.selectByParam(page,paramMap);
			}
			if("audit".equals(opType)){//审核中工单
				paramMap.put("workOrderStatus", WorkOrderStatus.Audit.getValue());
				cussWorkOrderList =cussWorkOrderService.selectByParam(page,paramMap);
			}
			if("closed".equals(opType)){//已关闭工单
				paramMap.put("workOrderStatus", WorkOrderStatus.Closed.getValue());
				cussWorkOrderList =cussWorkOrderService.selectByParam(page,paramMap);
			}	
			page=Page.setValue(page,cussWorkOrderList);
		}catch(Exception e){
			logger.error("客户专员查询工单数据时异常：",e);
		}		 	     
		return page;
	}		
		
	/**
	 * 问题图片上传
	 */		
	@RequestMapping(value = "/fileUpload", produces = "text/html;charset=UTF-8")
    public void fileUpload(HttpServletRequest request, HttpServletResponse actioncontext) throws Exception{
        String path=null;
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        MultipartFile imgFile1 = multipartRequest.getFile("file");// 获取上次文件名
        List<String> fileTypes = new ArrayList<String>();
        fileTypes.add("jpg");
        fileTypes.add("jpeg");
        fileTypes.add("bmp");
        fileTypes.add("gif");
        if (!LangUtil.isEmpty(imgFile1.getOriginalFilename())) {           
            File file1 = this.getFile(imgFile1,fileTypes);            
            path=request.getContextPath() +file1.toString();
            logger.info("method fileUpload result path= {}", path);            
        }
        actioncontext.setContentType("text/html; charset=UTF-8");
        PrintWriter out;
        try {
            out = actioncontext.getWriter();
            out.println(path);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    private File getFile(MultipartFile imgFile, List<String> fileTypes) throws Exception{
        String fileName = imgFile.getOriginalFilename();
        String ext = fileName.substring(fileName.lastIndexOf(".") + 1,fileName.length());
        ext = ext.toLowerCase();

        File file = null;
        if (fileTypes.contains(ext)) { 
            String fileName2 = CommonUtil.generateSequenceID()+"."+ext;//+fileName;
            String picpath = "/upload/"+fileName2;            
            file = new File(picpath);
            try {
                imgFile.transferTo(file); // 保存上传的文件
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return file;
    }
	
	
	/**
	 * 获取工单类型下拉框的初始值
	 */
	@RequestMapping("/InitCussWorkOrderType")
	public @ResponseBody List<Map<String,Object>> InitCussWorkOrderType(HttpServletRequest request){
		List<Map<String,Object>> cussWorkOrderTypeList=null;
		String parentType=request.getParameter("parentType");
		if(LangUtil.isEmpty(parentType)){
			//找为父类的工单类型
			cussWorkOrderTypeList=cussWorkOrderService.selectByParentType(-1);
		}
		else{ 
			//根据父工单类型找子工单类型
			cussWorkOrderTypeList=cussWorkOrderService.selectByParentType(Integer.valueOf(parentType));
		}
		return cussWorkOrderTypeList;
	}	
	
	/**
	 * 获取处理人下拉框的初始值 
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping("/InitHandler")
	public @ResponseBody BlockingQueue<UserVO> InitHandler(HttpServletRequest request){
		BlockingQueue<UserVO> handlerQueue=null;		
		try{			
		    //缓存中获取			
		    handlerQueue=(LinkedBlockingQueue<UserVO>)redisCacheService.get(Constant.WORK_ORDER_HANDLER_QUEUE);
		    if("appoint".equals(request.getParameter("appoint"))){
		    	handlerQueue.remove(new UserVO(AuthenticationUtils.getCurrentUser().getUserUMID()));
		    }
		    logger.info("method InitHandler result = {}", handlerQueue);
		}catch (Exception e) {
			logger.error("获取处理人下拉框的值时异常：", e);
		} 
		return handlerQueue;
	}
	
	/**
	 * 初始化工单类型下拉框树
	 * @param request
	 */
	@RequestMapping("/InitOrderTypeTree")
	public @ResponseBody String InitOrderTypeTree(HttpServletRequest request) throws Exception {	
		String json ="";
		try{
			List<Map<String,Object>> list =cussWorkOrderService.selectAllType();//数据库中获取源数据 
			json = JSONObject.toJSONString(list);
			logger.error("method InitOrderTypeTree result = {}", json);
		}catch(Exception e){
			logger.error("初始化工单类型下拉框树时异常：", e);
		}
		return json; 
	}
	
	/**
	 * 根据工单号，获取处理记录信息
	 * @param iWorkOrder
	 */
	@RequestMapping("/queryDealRecords")
	public @ResponseBody Page  queryDealRecords(HttpServletRequest request){
		
		String temppage=request.getParameter("currentPage");
		Integer pageSize=50;  
		Page page = Page.initPage(temppage,pageSize);
		try{
			Integer idWorkOrder=Integer.valueOf(request.getParameter("idWorkOrder"));
			List<CussWorkOrderDealflow> list =cussWorkOrderService.selectByIdWorkOrder(page,idWorkOrder);
			logger.error("method queryDealRecords result = {}", list);
			page=Page.setValue(page,list);
		}catch(Exception e){
			logger.error("获取处理意见时异常：", e);
		}		
		return page;
	}
	
	/**
	 * 进入工单处理页
	 */
	@RequestMapping("/intodeal")    
	public ModelAndView intoCussWorkOrderDeal(HttpServletRequest request){
		String workOrderId=request.getParameter("workOrderId");
		String opType=request.getParameter("opType");
		String workOrderStatus=request.getParameter("workOrderStatus");
		String channelSource=request.getParameter("channelSource");
		CussWorkOrder cussWorkOrder=null;
		if(!LangUtil.isEmpty(workOrderId)){
			//根据工单id，找工单信息						
			try {
				cussWorkOrder=cussWorkOrderService.getCussWorkOrder(Integer.valueOf(workOrderId));
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("opType", opType);
			request.setAttribute("workOrderStatus", workOrderStatus);
			request.setAttribute("channelSource", channelSource);
			return new ModelAndView("executive/deal","cussWorkOrder",cussWorkOrder);
		}
		return new ModelAndView("executive/deal");
	}			
	
	/**
	 * 工单处理
	 * @param 
	 */
	@RequestMapping("/deal")
	public @ResponseBody String cussWorkOrderDeal(HttpServletRequest request){
		String workOrderStatus=request.getParameter("workOrderStatus");
		Map<String,String> paramMap=new HashMap<String,String>();
		paramMap.put("dealType", request.getParameter("dealType"));
		paramMap.put("idWorkOrder", request.getParameter("idWorkOrder"));
		paramMap.put("currHandlerUm", AuthenticationUtils.getCurrentUser().getUserUMID());
		paramMap.put("currHandlerName", AuthenticationUtils.getCurrentUser().getUsername());
		paramMap.put("currHandlerRole", AuthenticationUtils.getCurrentUser().getUserRole());
		paramMap.put("nextHandlerUm", request.getParameter("workOrderHandlerUm"));
		paramMap.put("operateFlowLog", request.getParameter("operateFlowLog"));
		paramMap.put("urgentPriority", request.getParameter("urgentPriority"));
		paramMap.put("channelSource", request.getParameter("channelSource"));
		paramMap.put("feedbackToCustomer", request.getParameter("feedbackToCustomer"));
		try{
			if("submit".equals(request.getParameter("dealType"))){ //提交
				cussWorkOrderService.submitCussWorkOrder(paramMap);
			}	
			if("appoint".equals(request.getParameter("dealType"))){ //指派
				cussWorkOrderService.appointCussWorkOrder(paramMap);
			}
			if("closed".equals(request.getParameter("dealType"))){ //关闭				
				cussWorkOrderService.closedCussWorkOrder(paramMap);				
			}	
			if("urgent".equals(request.getParameter("dealType"))){ //紧急度
				cussWorkOrderService.changUrgentCussWorkOrder(paramMap);				
			}			
			if("4".equals(workOrderStatus)||"11".equals(workOrderStatus)){ //针对已分配待处理或审核未通过工单
				pendingWorkOrderDeal(paramMap);
			}
			if("6".equals(workOrderStatus)){  //针对处理中工单
				inHandWorkOrderDeal(paramMap);
			}
			return StatusEnum.success.getCode();
		}catch(Exception e){
			logger.error("客户专员处理工单，工单处理【阶段："+request.getParameter("dealType")+"】时异常：", e);
			return StatusEnum.fail.getCode();
		}
	}
	
	/**
	 * 已分配待处理工单处理
	 * @param paramMap
	 * @throws Exception 
	 */
	public void pendingWorkOrderDeal(Map<String,String> paramMap) throws Exception{	
		if("inHand".equals(paramMap.get("dealType"))){ //处理中
			cussWorkOrderService.inHandCussWorkOrder(paramMap);
		}
		if("applyBack".equals(paramMap.get("dealType"))){ //打回
			cussWorkOrderService.applyBackCussWorkOrder(paramMap);
		}		
	}
	
	/**
	 * 处理中状态的工单处理
	 * @param paramMap
	 * @throws Exception 
	 */
	public void inHandWorkOrderDeal(Map<String,String> paramMap) throws Exception{
		String dealType=paramMap.get("dealType");
		if("completed".equals(dealType)){ //已完成或提交审核
			cussWorkOrderService.completedCussWorkOrder(paramMap);
		}		
	}
	
	/**
	 * 进入问题最终结果反馈页
	 */
	@RequestMapping("/intofeedback")
	public ModelAndView intofeedback(){
		return new ModelAndView("result");
	}
	
	/**
	 * 进入工单查看页
	 */
	@RequestMapping("/intoShow")    
	public ModelAndView intoShowPage(HttpServletRequest request){
		String workOrderId=request.getParameter("workOrderId");
		String workOrderStatus=request.getParameter("workOrderStatus");
		String channelSource=request.getParameter("channelSource");
		CussWorkOrder cussWorkOrder=null;
		if(!LangUtil.isEmpty(workOrderId)){
			//根据工单id，找工单信息						
			try {
				cussWorkOrder=cussWorkOrderService.getCussWorkOrder(Integer.valueOf(workOrderId));
			} catch (Exception e) {
				e.printStackTrace();
			}
			request.setAttribute("workOrderStatus", workOrderStatus);
			request.setAttribute("channelSource", channelSource);
			return new ModelAndView("executive/show","cussWorkOrder",cussWorkOrder);
		}
		return new ModelAndView("executive/show");
	}	
	
	/**
	 * 根据类型查询工单信息
	 * @author 胡启萌
	 * @date 2015年9月15日
	 */
	private CussWorkOrderQueryVO queryWorkOrderByType(CussWorkOrderQueryVO vo, WorkOrderStatus status){
		switch (status) {
			case Audit:
			case Approved:
				vo.setIsApprove(Constant.ValidFlag.Y.toString());
				break;
			default:
				break;
		}
		vo.setWorkOrderStatus(status.getValue());
		return queryWorkOrder(vo);
	}
	
	/**
	 * 查询工单信息
	 * @author 胡启萌
	 * @date 2015年9月15日
	 */
	private CussWorkOrderQueryVO queryWorkOrder(CussWorkOrderQueryVO vo){
		AppUser user = AuthenticationUtils.getCurrentUser();
		vo.setCurrOperatorUm(user.getUserUMID());
		List<CussWorkOrder> list = cussWorkOrderService.selectListByPage(vo);
		Page.setValues(vo, list);
		return vo;
	}
}
